package com.example.common.security.filter;

import com.example.common.security.exception.CaptchaException;
import com.example.common.utils.RequestContextUtil;
import com.wf.captcha.utils.CaptchaUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: springsecurity-study
 * @description: 图形验证码过滤器
 * @author: ChenZhiXiang
 * @create: 2019-07-28 22:00
 **/
public class MyValidateCodeFilter extends OncePerRequestFilter {

    // 失败处理器
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 保证是登录请求且是POST方法
        if (StringUtils.equals("/szqy/login",httpServletRequest.getRequestURI()) &&
                StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(),"post")){
            try {
                validate();
            }catch (CaptchaException e){
                // 用失败处理器处理
                authenticationFailureHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
                return;
            }
        }
        // 放过，紧接其他处理器处理
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    private void validate() throws ServletRequestBindingException {
        //存在session的验证码
        String captcha = (String) RequestContextUtil.getRequest().getSession().getAttribute("captcha");
        // 表单提交的验证码
        String formImageCode = ServletRequestUtils.getStringParameter(RequestContextUtil.getRequest(),"imageCode");
        if (StringUtils.isBlank(formImageCode)){
            throw new CaptchaException("验证码不能为空");
        }
        if (StringUtils.isBlank(captcha)){
            throw new CaptchaException("验证码不存在");
        }
        if (!CaptchaUtil.ver(formImageCode,RequestContextUtil.getRequest())){
            throw new CaptchaException("验证码不正确");
        }
        // 验证码成功需要把验证码移除
        RequestContextUtil.getRequest().getSession().removeAttribute("captcha");
    }

    public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
        this.authenticationFailureHandler = authenticationFailureHandler;
    }
}
